#!/bin/bash

# 检查脚本参数是否正确
if [ "$#" -ne 3 ]; then
    echo "使用方式：$0 [挂载|卸载] 本地挂载点 [用户名:密码@网盘地址:端口]"
    exit 1
fi

# 提取参数
action="$1"
local_mount_point="$2"
webdav_url="$3"

# 根据WebDAV URL提取用户名、密码、网盘地址和端口
username=$(echo $webdav_url | awk -F ':' '{print $1}')  
password=$(echo $webdav_url | awk -F '@' '{print $2}' | awk -F ':' '{print $2}')  
remote_address=$(echo $webdav_url | awk -F '@' '{print $3}' | awk -F ':8' '{print $1}' | cut -d'/' -f3-)  
port=$(echo $webdav_url | awk -F ':' '{print $4}') 


# 输出提取的信息
echo "操作：$action"
echo "本地挂载点：$local_mount_point"
echo "用户名：$username"
echo "密码：$password"
echo "WebDAV网盘地址：$remote_address"
echo "端口号：$port"

# 检查动作是挂载还是卸载
if [ "$action" = "挂载" ]; then
    # 检查 $local_mount_point 路径是否存在  
    if [ ! -d "$local_mount_point" ]; then  
        # 如果路径不存在，则创建路径  
        mkdir -p "$local_mount_point"  
    fi  

    # 挂载 WebDAV
    sudo mount.davfs -o Username=$username,Password=$password,port=$port $remote_address $local_mount_point
    if [ $? -eq 0 ]; then
        echo "WebDAV 成功挂载到 $local_mount_point"
    else
        echo "挂载失败"
        exit 1
    fi
elif [ "$action" = "卸载" ]; then
    # 卸载 WebDAV
    sudo umount "$local_mount_point"
    rm -rf "$local_mount_point"
    if [ $? -eq 0 ]; then
        echo "WebDAV 成功从 $local_mount_point 卸载"
    else
        echo "卸载失败"
        exit 1
    fi
else
    echo "未知动作：$action，请输入 '挂载' 或 '卸载'"
    exit 1
fi

exit 0

